package com.xiaoyu.binaryTree;

/**
 * @program: DS_and_A
 * @description:
 * 给定两个二叉树，想象当你将它们中的一个覆盖到另一个上时，两个二叉树的一些节点便会重叠。
 *
 * 你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠，那么将他们的值相加作为节点合并后的新值，
 * 否则不为NULL 的节点将直接作为新二叉树的节点。
 *
 * 示例1:
 *
 * 输入:
 * 	Tree 1                     Tree 2
 *           1                         2
 *          / \                       / \
 *         3   2                     1   3
 *        /                           \   \
 *       5                             4   7
 * 输出:
 * 合并后的树:
 * 	     3
 * 	    / \
 * 	   4   5
 * 	  / \   \
 * 	 5   4   7
 *
 *
 * @author: YuWenYi
 * @create: 2021-06-06 10:35
 **/
public class MergeTrees_617 {

    //dfs究极大法!  -->  自己的写法
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;
        return  dfs(root1, root2);
    }
    public TreeNode dfs(TreeNode root1, TreeNode root2){
        if (root1 == null && root2 == null) return null;
        TreeNode res = new TreeNode(0);  //每次都需要新创建一个结点
        if (root1 == null || root2 == null){
            res.val = root1==null ? root2.val : root1.val;
            res.left = root1==null ? dfs(null, root2.left) : dfs(root1.left, null);
            res.right = root1==null ? dfs(null, root2.right) : dfs(root1.right, null);
        }else {
            res.val = root1.val + root2.val;
            res.left = dfs(root1.left, root2.left);
            res.right = dfs(root1.right, root2.right);
        }
        return res;  //每次都把加好的结果return回去
    }

    //更简洁版本:
    public TreeNode mergeTrees1(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        if (root2 == null) return root1;
        TreeNode merged = new TreeNode(root1.val + root2.val);
        merged.left = mergeTrees1(root1.left, root2.left);
        merged.right = mergeTrees1(root1.right, root2.right);
        return merged;
    }


    public static void main(String[] args) {
        TreeNode right = new TreeNode(2,new TreeNode(3),new TreeNode(4));
        TreeNode left = new TreeNode(5,new TreeNode(6),new TreeNode(7));
        TreeNode root1 = new TreeNode(1,left,right);

        TreeNode right2 = new TreeNode(2, new TreeNode(3),null);
        TreeNode left2 = new TreeNode(5,new TreeNode(6),new TreeNode(7));
        TreeNode root2 = new TreeNode(1,left2,right2);

        MergeTrees_617 mergeTrees_617 = new MergeTrees_617();
        TreeNode node = mergeTrees_617.mergeTrees(root1, root2);

        LevelOrder_102.simpleLevelOrder(node);

    }
}
